<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/4/004
 * Time: 10:37
 */

namespace Admin\Model;

use Think\Model;
class GoodsModel extends Model
{
    protected $selectFields = ['id', 'goods_sn', 'goods_name', 'price', 'storage', 'goods_img', 'sale_num', 'is_on_sale'];
    protected $insertFields = array('goods_sn','goods_name','price','storage','goods_description','content','goods_img','sale_num','is_on_sale');
    protected $updateFields = array('id','goods_sn','goods_name','price','storage','goods_description','content','goods_img','sale_num','is_on_sale');

    protected $_validate = array(
        array('goods_name', 'require', '商品名称不能为空！', 1, 'regex', 3),
        array('goods_name', '1,80', '商品名称 80 个字符以内！', 1, 'length', 3),
        array('goods_sn', '1, 50', '', 2, 'length', 3),//不为空验证 为空系统自动生成货号
        array('goods_img', 'require', '商品主图不能为空！', 1, 'regex', 3),
        array('price', 'require', '商品价格不能为空！', 1, 'regex', 3),
        array('price', 'currency', '商品价格必须是货币格式！', 2, 'regex', 3),
        array('storage', 'require', '库存数量不能为空！', 1, 'regex', 3),
        array('storage', 'number', '库存数量参数有误！', 1, 'regex', 3),
        array('goods_description', '1,200', '商品描述 200个字符以内！', 2, 'length', 3),
        array('is_on_sale', 'number', '是否上架参数有误！', 1, 'regex', 3),
        array('is_on_sale', '0,1', '是否上架参数有误！', 1, 'in', 3),
    );

    protected function _before_insert(&$data, $option){
        $data['add_time'] = time();
        $data['price'] = yuan_to_fen($data['price']);

        //处理商品货号
        $post_goods_sn = I('post.goods_sn','');
        $create_goods_sn = 'HH'.date('ymds').mt_rand(1000,9999);
        $data['goods_sn']= $post_goods_sn ? $post_goods_sn : $create_goods_sn;
    }

    protected function _before_update(&$data, $option){
        $data['update_time'] = time();
        $data['price'] = yuan_to_fen($data['price']);
    }

    //获取商品列表
    public function getGoodsList($where, $field = null, $order = 'add_time desc') {
        if ($field == null) {
            $field = $this->selectFields;
        }

        $count = $this->where($where)->count();
        $pageData = get_page($count, 15);

        $list = $this->where($where)->field($field)->order($order)->limit($pageData['limit'])->select();

        return ['list'=>$list, 'count'=>$count];
    }
}